//
//  YijiaViewController.m
//  HomeIn
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 ZZP. All rights reserved.
//

#import "YijiaViewController.h"
#import "YijiaModel.h"
#import "YijiaCellOne.h"
#import "YijiaCellTwo.h"
#import "YijiaDetailViewController.h"

@interface YijiaViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, retain) NSMutableArray *modelArray;//model数组
@property (nonatomic, retain) YijiaModel *picModel;

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) UILabel *label;

@property (nonatomic, assign) NSInteger currentPage;//记录当前page
@property (nonatomic, assign) NSInteger currentPage1;
@property (nonatomic, assign) BOOL isUpLoading;//标记是否为上拉

@end

@implementation YijiaViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //视图将要出现的时候刷新
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.modelArray = [NSMutableArray array];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 113 - 30)  style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.tableView];
    
    //取消cell线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //头部
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4 + 30 * HEIGHTSCALE)];
    self.tableView.tableHeaderView = headerView;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(Action:)];
    [headerView addGestureRecognizer:tap];
    headerView.userInteractionEnabled = YES;
    //图片
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4)];
    [headerView addSubview:self.imageView];
    //标题
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT / 4, WIDTH, 30 * HEIGHTSCALE)];
    [headerView addSubview:self.label];
    
    self.currentPage = 0;//默认请求下来的数据为第0-20页
    self.currentPage1 = 20;
    self.isUpLoading = NO;//默认是下拉状态
    [self addHeaderRefresh];
    [self addFooterRefresh];
   
}

-(void)Action:(UITapGestureRecognizer *)tap
{
    YijiaDetailViewController *yijiaDetailVC = [[YijiaDetailViewController alloc] init];
    yijiaDetailVC.model = self.picModel;//属性传值
    
    //push到详情的时候让tabBar(工具栏)消失
    yijiaDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:yijiaDetailVC animated:YES];
}

//方法传值
- (void)sendPicModel
{
    [self.imageView sd_setImageWithURL:[NSURL URLWithString:self.picModel.imgsrc]];
    self.label.text = self.picModel.title;
}

//下拉刷新
- (void)addHeaderRefresh
{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        self.isUpLoading = NO;//标记为下拉
        NSLog(@"下拉");
        self.currentPage = 0;//刷新首页,只要下拉,就请求第0-20页数据
        self.currentPage1 = 20;
        //重新请求数据
        [self getAFNetWorkingData:self.currentPage];
    }];
    
    // 马上进入刷新状态
    [self.tableView.header beginRefreshing];
}

//上拉刷新
- (void)addFooterRefresh
{
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        self.isUpLoading = YES;//标记为上拉
        NSLog(@"上拉");
        self.currentPage += 20;//上拉一次,页码+20
        self.currentPage1 += 20;
        
        [self getAFNetWorkingData:self.currentPage];
    }];
    
}


- (void)getAFNetWorkingData:(NSInteger)page
{
    
    NSString *urlString = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/T1348654105308/%ld-%ld.html", self.currentPage, self.currentPage1];
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //下拉时,删除之前的,存入最新的数据
        if (self.isUpLoading == NO)
        {
            //如果是下拉刷新,清空数组
            [self.modelArray removeAllObjects];
            
        }
        //上拉刷新,则往数组里增加,页面上也增加
        NSMutableDictionary *dictionary = responseObject;
        NSMutableArray *array = [dictionary objectForKey:@"T1348654105308"];
        
        for (NSMutableDictionary *dic in array) {
            
            YijiaModel *yijiaModel = [[YijiaModel alloc] init];
            [yijiaModel setValuesForKeysWithDictionary:dic];

            
            NSMutableArray *imgextraArray = [dic objectForKey:@"imgextra"];
            if (imgextraArray != nil) {
                
                yijiaModel.imgextra = [NSMutableArray array];
                NSMutableDictionary *Dic = [imgextraArray objectAtIndex:0];
                NSMutableDictionary *Dic1 = [imgextraArray objectAtIndex:1];
                NSString *str = [Dic objectForKey:@"imgsrc"];
                NSString *str1 = [Dic1 objectForKey:@"imgsrc"];
                
                [yijiaModel.imgextra addObject:str];
                [yijiaModel.imgextra addObject:str1];
                
            }
            [self.modelArray addObject:yijiaModel];

        }
        
        self.picModel = [self.modelArray objectAtIndex:0];//数组中第一个元素单独储存
        [self sendPicModel];//方法传值
        [self.modelArray removeObjectAtIndex:0];//删除数组中第一个元素
        
        //结束下拉上拉刷新
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        
        //刷新
        [self.tableView reloadData];

    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"error = %@",error);
             
         }];

}

//指定分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

//指定多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  
    return self.modelArray.count;
 
}

//创建一个cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    YijiaModel *model = [self.modelArray objectAtIndex:indexPath.row];
    //恢复cell线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    
    if (model.imgextra == nil) {
        
        static NSString *cellIndentifier = @"cell1";
        YijiaCellOne *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil)
        {
            cell = [[YijiaCellOne alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//设置cell点击效果 (没有置灰效果)
        
        cell.model = model;
        return cell;
        
    } else {
        
        static NSString *cellIndentifier = @"cell2";
        YijiaCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
        if (cell == nil)
        {
            cell = [[YijiaCellTwo alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
        }
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;//设置cell点击效果 (没有置灰效果)
        
        cell.model = model;
        return cell;
    }
    
    
}

//设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 100 * HEIGHTSCALE;
    
}

//点击cell触发方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YijiaDetailViewController *yijiaDetailVC = [[YijiaDetailViewController alloc] init];
    YijiaModel *model = [self.modelArray objectAtIndex:indexPath.row];
    yijiaDetailVC.model = model;//属性传值

    //push到详情的时候让tabBar(工具栏)消失
    yijiaDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:yijiaDetailVC animated:YES];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
